<template>
    <div class="flex-box">
        <div class="flex-header">
            <button class="sea-btn-icon" @click="reload" title="撤销编辑，退回原始状态">
                <i class="fa fa-fw fa-reply"></i>
            </button>
            <button class="sea-btn-icon" @click="props.save" title="保存当前代码">
                <i class="fa fa-fw fa-save"></i>
            </button>
            <button class="sea-btn-icon" @click="changeTheme" title="夜间/白天风格">
                <i style="font-size: 17px;" class="fa fa-fw fa-lightbulb-o"></i>
            </button>

            <i class="divider-vertical margin-right"></i>

            <h5>绩效考察</h5>
        </div>
        <div class="flex-body">
            <codemirror style="height: 100%"
                        v-model="content" @change="onchange"
                        :autofocus="true" :extensions="extensions"/>
            <div>
                <p v-for="(error, index) in errors" :key="index">
                    ⚠️ {{ error }}
                </p>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import {ref, watch, computed} from 'vue'
import {java} from '@codemirror/lang-java'
import {Extension} from '@codemirror/state'
import {Codemirror} from 'vue-codemirror'
import {oneDark} from '@codemirror/theme-one-dark'

/**
 * 代码编辑器：properties
 *
 * 一些需要动态配置的系统参数，会用到这个组件
 */
interface Props {
    /** model-value */
    value: string;
    /** 保存当前代码 */
    save: Function;
}

// 使用 withDefaults 设置默认值
const props = withDefaults(defineProps<Props>(), {
    value: '# 示例配置\nserver.host=localhost\nserver.port=8080\ndebug=true', save: () => {
    }
})

const content = ref(props.value)
const errors = ref<string[]>([])


// 可用主题列表
const themes = {
    default: [],
    dark: [oneDark]
}

const isDarkTheme = ref(true)

// CodeMirror 扩展配置（仅保留语法高亮和主题）
const extensions = computed<Extension[]>(() => {
    return [java(), isDarkTheme.value ? themes.dark : themes.default];
})

const changeTheme = () => {
    isDarkTheme.value = !isDarkTheme.value;
    console.log(isDarkTheme.value)
}

// 验证 properties 格式
const onchange = (value: string) => {
    const lines = value.split('\n')
    const newErrors: string[] = []

    lines.forEach((line, index) => {
        // 跳过空行和注释
        if (!line.trim() || line.trim().startsWith('#')) return

        // 检查格式：key=value 或 key:value
        if (!/^[ \t]*[\w.-]+[ \t]*[=:][ \t]*.*/.test(line)) {
            newErrors.push(`第 ${index + 1} 行格式错误（正确示例：key=value）`)
        }
    })

    errors.value = newErrors
}

const reload = () => {
    content.value = props.value;
}

// 初始化验证
watch(() => props.value, (val) => {
    content.value = val
    onchange(val)
}, {immediate: true})

</script>
